//
//  MyCarPrintView.m
//  SecondPage
//
//  Created by xiong qi on 13-5-15.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "MyCarPrintView.h"
#import "../../Common/Common/ImagePrintHelp.h"
#import "../../HondaPro_2/aejoy/ConfigCodeHelper.h"
//#import "../../Honda3/LoginView/LoginView.h"
#import "../../ResourceLoader/ResourceLoader/ResourceLoader.h"
#import "../../HondaPro_2/aejoy/Categories/NetworkingViewController.h"
#import "../../HondaPro_2/aejoy/NetworkService/NetworkManager.h"

@interface MyCarPrintView()
@property (nonatomic, retain) NSDictionary *dataDic;
@end

@implementation MyCarPrintView

- (id)initWithFrame:(CGRect)frame functionBtnTitle:(NSString*)string
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor blackColor];
        
        UIImage *img=[UIImage imageNamed:@"AllAuto_Comparison_Image_BG"];
        img=[img stretchableImageWithLeftCapWidth:15 topCapHeight:12];
        
        backGroundView = [[UIImageView alloc] initWithFrame:CGRectMake(89, 33, 842+4, 595+4)];
        [self addSubview:backGroundView];
        backGroundView.userInteractionEnabled = YES;
        [backGroundView release];
        [backGroundView setImage:img];
        backGroundView.userInteractionEnabled = YES;
        
        contentView = [[UIView alloc] initWithFrame:CGRectMake(2, 2, 842, 595)];
        [backGroundView addSubview:contentView];
        [contentView release];
        
        carimageview = [[UIImageView alloc] initWithFrame:CGRectMake(60, 40, 330, 225)];
        [contentView addSubview:carimageview];
        [carimageview release];
        carimageview .contentMode = UIViewContentModeScaleAspectFit;
        
        // @chenms @0823
        companyimageview = [[UIImageView alloc] initWithFrame:CGRectMake(58, 15, 114, 30)];
        [contentView addSubview:companyimageview];
        [companyimageview release];
        
        carconfigimageview1 = [[MyCarItemView alloc] initWithFrame:CGRectMake(425, 40, 180, 150)];
        [contentView addSubview:carconfigimageview1];
        [carconfigimageview1 release];
        
        carconfigimageview2 = [[MyCarItemView alloc] initWithFrame:CGRectMake(425+180+20, 40, 180, 150)];
        [contentView addSubview:carconfigimageview2];
        [carconfigimageview2 release];
        
        carconfigimageview3 = [[MyCarItemView alloc] initWithFrame:CGRectMake(425, 40+150+20, 180, 150)];
        [contentView addSubview:carconfigimageview3];
        [carconfigimageview3 release];
        
        carconfigimageview4 = [[MyCarItemView alloc] initWithFrame:CGRectMake(425+180+20, 40+150+20, 180, 150)];
        [contentView addSubview:carconfigimageview4];
        [carconfigimageview4 release];

        carinfoimageview = [[MyCarParameterView alloc] initWithFrame:CGRectMake(60, 285, 228, 290)];
        [contentView addSubview:carinfoimageview];
        [carinfoimageview release];
        
        
        logoView = [[UIImageView alloc] initWithFrame:CGRectMake(contentView.bounds.size.width - 195 -  30, 419, 195, 41)];
        [contentView addSubview:logoView];
        [logoView release];
        logoView.image = [UIImage imageNamed:@"AllAuto_Honda@2x~ipad"];
        
        //特约店信息
        storeimageview = [[UIImageView alloc] initWithFrame:CGRectMake(425, 380, 180, 160)];
        storeimageview.clipsToBounds = NO;
        [contentView addSubview:storeimageview];
        [storeimageview release];
        
        {
            NSDictionary * localdic = [ConfigCodeHelper shareInstance].localDic;
//            NSDictionary * salerInfo = [LoginView shareInstance].salerInfo;
            
            UIFont * font = [UIFont fontWithName:@"Arial-BoldMT" size:12];
            int width = storeimageview.frame.size.width;
            NSString * text = [localdic objectForKey:@"name"];
            
            UILabel * titleLabel = [[UILabel alloc] init];
            titleLabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
            titleLabel.textAlignment = NSTextAlignmentLeft;
            titleLabel.font = font;
            [titleLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:titleLabel];
            [titleLabel release];
            titleLabel.text = text;
            titleLabel.frame = CGRectMake(0, 0, width + 200.0, 30);
            
            
            font = [UIFont fontWithName:@"Arial" size:10];
            UILabel * textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, titleLabel.frame.size.height+5, 30, 14)];
            textLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
            textLabel.textAlignment = NSTextAlignmentLeft;
            textLabel.font = font;
            [textLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:textLabel];
            [textLabel release];
            textLabel.text = @"地址：";
            
            text = [localdic objectForKey:@"address"];
            width = storeimageview.frame.size.width-30;
            UILabel * addressLabel = [[UILabel alloc] init];
            addressLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
            addressLabel.textAlignment = NSTextAlignmentLeft;
            addressLabel.font = font;
            addressLabel.numberOfLines = 0;
            [addressLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:addressLabel];
            [addressLabel release];

            addressLabel.text = text;
            addressLabel.frame = CGRectMake(30, textLabel.frame.origin.y, width, [self caculateTitleHeight:text Font:font Width:width]);
            
            textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, addressLabel.frame.origin.y+addressLabel.frame.size.height+5, storeimageview.frame.size.width, 12)];
            textLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
            textLabel.textAlignment = NSTextAlignmentLeft;
            textLabel.font = [UIFont fontWithName:@"Arial" size:10];
            [textLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:textLabel];
            [textLabel release];
            textLabel.text = [NSString stringWithFormat:@"邮编：%@",[localdic objectForKey:@"zipcode"]];
            
            textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, textLabel.frame.origin.y+textLabel.frame.size.height+5, storeimageview.frame.size.width, 12)];
            textLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
            textLabel.textAlignment = NSTextAlignmentLeft;
            textLabel.font = [UIFont fontWithName:@"Arial" size:10];
            [textLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:textLabel];
            [textLabel release];
            NSString *homepage = [localdic objectForKey:@"homepage"];
            homepage = (homepage && [homepage stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length > 0) ? homepage : @"www.ghac.cn";
            textLabel.text = [NSString stringWithFormat:@"网址：%@", homepage];
            
            textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, textLabel.frame.origin.y+textLabel.frame.size.height+5, storeimageview.frame.size.width, 14)];
            textLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
            textLabel.textAlignment = NSTextAlignmentLeft;
            textLabel.font = [UIFont fontWithName:@"Arial" size:10];
            [textLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:textLabel];
            [textLabel release];
            textLabel.text = [NSString stringWithFormat:@"免费服务热线：%@",[localdic objectForKey:@"tel"]];
            
            textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, textLabel.frame.origin.y+textLabel.frame.size.height+5, storeimageview.frame.size.width, 14)];
            textLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
            textLabel.textAlignment = NSTextAlignmentLeft;
            textLabel.font = [UIFont fontWithName:@"Arial" size:10];
            [textLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:textLabel];
            [textLabel release];
//            textLabel.text = [NSString stringWithFormat:@"联系人：%@",[salerInfo objectForKey:@"salerName"]];
            
            textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, textLabel.frame.origin.y+textLabel.frame.size.height+5, storeimageview.frame.size.width, 14)];
            textLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
            textLabel.textAlignment = NSTextAlignmentLeft;
            textLabel.font = [UIFont fontWithName:@"Arial" size:10];
            [textLabel setBackgroundColor:[UIColor clearColor]];
            [storeimageview addSubview:textLabel];
            [textLabel release];
//            textLabel.text = [NSString stringWithFormat:@"联系电话：%@",[salerInfo objectForKey:@"tel"]];

        }
        
        UILabel *declareLabel = [[UILabel alloc] initWithFrame:CGRectMake(storeimageview.frame.origin.x, contentView.bounds.size.height - 42 - 14, 390, 14)];
        declareLabel.textColor = [UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:0.608];
        declareLabel.textAlignment = NSTextAlignmentLeft;
        declareLabel.font = [UIFont fontWithName:@"Arial" size:10];
        [declareLabel setBackgroundColor:[UIColor clearColor]];
        [contentView addSubview:declareLabel];
        [declareLabel release];
        declareLabel.text = [NSString stringWithFormat:@"本产品样本的全部内容，以实车为准。%@保留最终解释权和修改权。", @"广汽集团乘用车有限公司"];
        
        btnCancel = [[UIButton alloc] initWithFrame:CGRectMake(backGroundView.frame.origin.x + 260, backGroundView.frame.origin.y + backGroundView.bounds.size.height + 18, 155, 44)];
        [self addSubview:btnCancel];
        [btnCancel release];
        [btnCancel setBackgroundImage:[UIImage imageNamed:@"AllAuto_Config_Button_Unselect"] forState:UIControlStateNormal];
        [btnCancel setBackgroundImage:[UIImage imageNamed:@"AllAuto_Config_Button_Select"] forState:UIControlStateHighlighted];
        [btnCancel setTitle:@"返 回" forState:UIControlStateNormal];
        [btnCancel setTitleColor:[UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0] forState:UIControlStateNormal];
        [btnCancel setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [btnCancel addTarget:self action:@selector(onCancel:) forControlEvents:UIControlEventTouchUpInside];
        
        btnPrint = [[UIButton alloc] initWithFrame:CGRectMake(backGroundView.frame.origin.x + 433, backGroundView.frame.origin.y + backGroundView.bounds.size.height + 18, 155, 44)];
        btnPrint.tag = [string isEqualToString:@"打 印"]? 0 : 1;
        [self addSubview:btnPrint];
        [btnPrint release];
        [btnPrint setBackgroundImage:[UIImage imageNamed:@"AllAuto_Config_Button_Unselect"] forState:UIControlStateNormal];
        [btnPrint setBackgroundImage:[UIImage imageNamed:@"AllAuto_Config_Button_Select"] forState:UIControlStateHighlighted];
        [btnPrint setTitle:string forState:UIControlStateNormal];
        [btnPrint setTitleColor:[UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0] forState:UIControlStateNormal];
        [btnPrint setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [btnPrint addTarget:self action:@selector(onPrint:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

-(CGFloat)caculateTitleHeight:(NSString*)title Font:(UIFont*)font Width:(int)width
{
    
    if (title == nil ||[title isEqualToString:@""]) {
        return 0;
    }
    
    CGSize labelSize = [title sizeWithFont:font constrainedToSize:CGSizeMake(width, 1000) lineBreakMode:NSLineBreakByWordWrapping];
    
    float height = labelSize.height;
    
    return height;
}

-(void)SetCarImage:(UIImage *)image
{
    carimageview.image = image;
}

-(void)SetCarConfigImage:(NSDictionary *)dic Index:(int)index
{
    switch (index) {
        case 1:
            carconfigimageview1.dataSource = dic;
            [carconfigimageview1 SetData];
            break;
        case 2:
            carconfigimageview2.dataSource = dic;
            [carconfigimageview2 SetData];
            break;
        case 3:
            carconfigimageview3.dataSource = dic;
            [carconfigimageview3 SetData];
            break;
        case 4:
            carconfigimageview4.dataSource = dic;
            [carconfigimageview4 SetData];
            break;
            
        default:
            break;
    }
}

-(void)SetCarInfoImage:(NSDictionary *)dic
{
    carinfoimageview.dataSource = dic;
    carinfoimageview.autoID = self.autoID;
    [carinfoimageview SetData];
//    carinfoimageview.image = image;
    self.dataDic = dic;
    
    // @chenms @0906
    int isNotHonda = [[dic objectForKey:CarInfo_IsNotHonda] intValue];
    companyimageview.image = [UIImage imageNamed:isNotHonda ? ResourceLoader_CarExtra_CompanyLogoNameSpecial : ResourceLoader_CarExtra_CompanyLogoNameNormal];

}

-(void)onCancel:(UIButton *)sender
{
    [UIView animateWithDuration:0.5
                     animations:^{
                         
                         self.alpha = 0;
                         
                     }
                     completion:^(BOOL finished){

                         [self removeFromSuperview];
                     }];

}

-(void)onPrint:(UIButton *)sender
{
    ImagePrintHelp * help =[ImagePrintHelp getInstance];
    contentView.backgroundColor = [UIColor whiteColor];
    UIImage * image = [help GetViewThumbnailImage:contentView];
    
    if (0 == sender.tag) {
        contentView.backgroundColor = [UIColor clearColor];
        //    carimageview.image = image;
        [help PrintImage:image];
    } else {
        
        [[NetworkingViewController sharedController] showNetworkingWithTitle:nil content:@"努力发送中..." activiting:YES enableDismiss:NO];
        
        int date = (int)[[NSDate date] timeIntervalSince1970];
        NSString* iDs = [NSString stringWithFormat:@"%d%@", date, self.userEmail];
        
        NSDictionary* picDic = @{@"pic": [NSData dataWithData:UIImageJPEGRepresentation(image , 1)]};
        
        NSString* email = [[ConfigCodeHelper shareInstance].localDic objectForKey:@"email"];
        if (nil == email || 0 == email.length) {
            NSString* ghasno = [[ConfigCodeHelper shareInstance].localDic objectForKey:@"ghasno"];
            if (nil == ghasno || 0 == ghasno.length) {
                email = @"";
            } else {
                email = [NSString stringWithFormat:@"%@@ghac.cn", ghasno];
            }
        }
        
        NSString* fromName = [[ConfigCodeHelper shareInstance].localDic objectForKey:@"name"];
        if (nil == fromName || 0 == fromName.length) {
            fromName = @"";
        }
        
        NSMutableDictionary* emailInfoDic = [[[NSMutableDictionary alloc] init] autorelease];
        [emailInfoDic setObject:@"配置爱车" forKey:@"Subject"];
        [emailInfoDic setObject:email forKey:@"FromAddr"];
        [emailInfoDic setObject:fromName forKey:@"FromName"];
        [emailInfoDic setObject:iDs forKey:@"IDs"];
        [emailInfoDic setObject:self.userEmail forKey:@"Addresses"];
        [emailInfoDic setObject:@"我的配置" forKey:@"MailContent"];
        if ([picDic isKindOfClass:[NSDictionary class]]) {
            [emailInfoDic setObject:picDic forKey:@"pics"];
        }
        
//        NetworkTask* emailTask = [[NetworkTask alloc] initWithPostSendEmailUrl:@"http://58.62.201.242:8082/ipademail/postmail.ashx" emailData:emailInfoDic];
        NetworkTask* emailTask = [[NetworkTask alloc] initWithPostSendEmailUrl:[NSString stringWithFormat:@"http://%@:8080/ipademail/postmail.ashx", [NetworkManager getInstance].host] emailData:emailInfoDic];
        emailTask.indentifier = @"Sending_Email";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSendEmailSuccess:) name:NetworkTask_NotificationName_OnSuccess object:emailTask];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSendEmailFailed:) name:NetworkTask_NotificationName_OnFail object:emailTask];
        [[NetworkManager getInstance] startTaskAsync:emailTask];
        SafeRelease(emailTask);
        
    }
}

- (void)onSendEmailSuccess:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    if (![task isKindOfClass:[NetworkTask class]] || 0 != [[task.resultDict objectForKey:@"error_code"] intValue]) {
        NSString* result = [task.resultDict objectForKey:@"error_msg"];
        [[NetworkingViewController sharedController] showNetworkingWithTitle:nil content:result activiting:NO enableDismiss:YES];
        return;
    }
    
    if ([@"Sending_Email" isEqualToString:task.indentifier]) {
        [[NetworkingViewController sharedController] showNetworkingWithTitle:nil content:@"邮件发送完成" activiting:NO enableDismiss:YES];
        return;
    }
}

- (void)onSendEmailFailed:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    [[NetworkingViewController sharedController] showNetworkingWithTitle:nil content:@"网络访问失败" activiting:NO enableDismiss:YES];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.autoID = nil;
    self.dataDic = nil;
    [super dealloc];
}

@end
